package com.hsmpay.mobile.ds.impl;

import com.hsmpay.common.pojo.BasePojo;
import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.dao.terminal.TchannelDao;
import com.hsmpay.mobile.dao.terminal.TchannelMDao;
import com.hsmpay.mobile.dao.trans.TransOrderDao;
import com.hsmpay.mobile.ds.DS_GuoTongService;
import com.hsmpay.mobile.pojo.terminal.Tchannel;
import com.hsmpay.mobile.pojo.terminal.TchannelM;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.qian4.pojo.BalanceResult;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.pojo.RevocationResult;
import com.hsmpay.qian4.pojo.send.SendParam;
import com.hsmpay.yl8583.service.EBCPayService;
import com.hsmpay.yl8583.service.GuoTongService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/7/14.
 */
@Service("ds_GuoTongService")
public class DS_GuoTongServiceImpl implements DS_GuoTongService<BasePojo,Long> {
    @Resource(name = "tchannelDao")
    TchannelDao<Tchannel, Long> tchannelDao;
    @Resource(name = "transOrderDao")
    private TransOrderDao<TransOrder, String> transOrderDao;//交易订单
    @Resource(name = "tchannelMDao")
    private TchannelMDao<TchannelM, String> tchannelMDao;//通道商户号表

    private Long flRoleId = 2l;
    private Long fdRoleId = 3l;
    private static int cnt = 0;
    private static int ECB_TchannelId = 33;
    /**
     * 得到密钥
     * @param tcm
     * @param str
     * @param transAmt
     * @param c_fdMoney
     * @return
     * @throws Exception
     */
    public Map<String, String> getMiYao(TchannelM tcm, String str, String transAmt, Double c_fdMoney) throws Exception {
        Map<String, String> miYao = null;
        if (StringUtils.isEmpty(str)) {
            miYao = reflushMiYao(tcm, transAmt, c_fdMoney);
        } else {
            miYao = new HashMap<String, String>();
            //if(StringUtils.isEmpty(str)) return reflushMiYao(transAmt,c_fdMoney);
            String[] strA = str.split("_");
            if ("-1".equals(strA[0]) || StringUtils.isEmpty(strA[2].trim()))
                return reflushMiYao(tcm, transAmt, c_fdMoney);
            miYao.put("batchId", strA[2]);
            miYao.put("pinKey", strA[3]);
            miYao.put("macKey", strA[4]);
            miYao.put("trkKey", strA[5]);
        }
        return miYao;
    }

    /**
     * 刷新密钥
     * @param tcm
     * @param transAmt
     * @param c_fdMoney
     * @return
     * @throws Exception
     */
    public Map<String, String> reflushMiYao(TchannelM tcm, String transAmt, Double c_fdMoney) throws Exception {
        GuoTongService aps = new GuoTongService(tcm.getMcode(), tcm.getTcode(), "000001", tcm.getMainKey(), null, null, null);

        Integer bankOrderNum = searchGuoTongTransId();
        String miyao = aps.login(bankOrderNum.toString());
        //保存密钥
        tchannelMDao.updateMobileTcOtherById(tcm.getId(), miyao);
        return getMiYao(tcm, miyao, transAmt, c_fdMoney);
    }

    /**
     * 获取交易码
     * @return
     */
    public Integer searchGuoTongTransId() throws SQLException {
        return transOrderDao.searchGuoTongTransId();
    }

    /**
     * 查余
     * @param send
     * @return
     * @throws Exception
     */
    public BalanceResult balanceEnquiry(Qian4SendLog send) throws Exception {
        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(), send.getTerminalId());
        Map<String, String> miyao = getMiYao(tcm, tcm.getOtherParam(), null, null);

        GuoTongService aps = new GuoTongService(send.getMerchantId(), send.getTerminalId(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"), miyao.get("trkKey"));//getAnxinybPayService(send.getTransAmt());
        Qian4SendLog sendParam = new Qian4SendLog();
        BeanUtils.copyProperties(sendParam, send);
        return aps.balanceEnquiry(sendParam);
    }

    /**
     * 交易
     * @param send
     * @param tc
     * @return
     * @throws Exception
     */
    public PurchaseResult billPayment(Qian4SendLog send, Tchannel tc) throws Exception {
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee() / tc.getFeeRate()));
        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(), send.getTerminalId());
        Map<String, String> miyao = getMiYao(tcm, tcm.getOtherParam(), send.getTransAmt(), c_fdMoney);
        GuoTongService aps = new GuoTongService(send.getMerchantId(), send.getTerminalId(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"), miyao.get("trkKey"));
        PurchaseResult rs = aps.billPayment(send);
        if("00A0".equals(rs.getReqCode())){
            miyao = reflushMiYao(tcm, send.getTransAmt(),c_fdMoney);
            aps = new GuoTongService(send.getMerchantId(), send.getTerminalId(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"), miyao.get("trkKey"));
            rs = aps.billPayment(send);
        }
        return rs;
    }

    /**
     * 初始化参数
     * @param send
     * @param tc
     * @return
     * @throws Exception
     */
    public Qian4SendLog initSend(Qian4SendLog send, Tchannel tc) throws Exception {
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee() / tc.getFeeRate()));
        GuoTongService aps = getGuoTongService(send.getTransAmt(), c_fdMoney);
        send.setCollectionType(tc.getCode());
        send.setBankOrderNum(searchGuoTongTransId().toString());//查询序列 获取动态流水号
        send.setBatchId(aps.batch);//批次号
        send.setMerchantId(aps.merchantId);
        send.setTerminalId(aps.terminalId);
        return send;
    }
    /**
     * 获得费率版支付接口
     *
     * @return
     * @throws Exception
     */
    public GuoTongService getGuoTongService(String transAmt, Double c_fdMoney) throws Exception {
        TchannelM tcm = getTchannelM(transAmt, c_fdMoney);

        Map<String, String> miyao = getMiYao(tcm, tcm.getOtherParam(), transAmt, c_fdMoney);
        //获取主密钥 和 终端号
        return new GuoTongService(tcm.getMcode(), tcm.getTcode(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"), miyao.get("trkKey"));
    }

    private TchannelM getTchannelM(String transAmt, Double c_fdMoney) throws Exception {
        TchannelM tcm = null;
        Double money = 0.00;
        if (StringUtils.isNotEmpty(transAmt)) {
            money = Integer.parseInt(transAmt) / 100.0;
        }
        Long roleId = flRoleId;
        if (money > c_fdMoney) roleId = fdRoleId;
        List<TchannelM> list = tchannelMDao.searchMobileTCListByCode(ECB_TchannelId, roleId);
        tcm = list.get(cnt % list.size());
        cnt++;
        return tcm;
    }

    /**
     * 冲正
     * @param send
     * @return
     * @throws Exception
     */
    public RevocationResult unBillPayment(Qian4SendLog send) throws Exception {
        Tchannel tc = tchannelDao.searchMobileTchannelByCode(send.getCollectionType());
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee() / tc.getFeeRate()));

        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(), send.getTerminalId());

        Map<String, String> miyao = getMiYao(tcm, tcm.getOtherParam(), send.getTransAmt(), c_fdMoney);
        //冲正  重新创建接口对象
        GuoTongService aps = new GuoTongService(send.getMerchantId(), send.getTerminalId(), miyao.get("batchId"), tcm.getMainKey(), miyao.get("pinKey"), miyao.get("macKey"), miyao.get("trkKey"));

        SendParam sendParam = new SendParam();
        BeanUtils.copyProperties(sendParam, send);
        RevocationResult rr = aps.unBillPayment(sendParam);
        return rr;
    }
}
